package com.yifeng.util;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class BlogResult<T> {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();
    private int code;
    private String msg;
    private T data;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public BlogResult() {
        this.code = 200;
        this.msg = "OK";
    }
    public BlogResult(T data)
    {
        this.data = data;
    }
    public BlogResult(int code,String msg)
    {
        this.code = code;
        this.msg = msg;
    }
    public BlogResult(int code,T data)
    {
        this.code = code;
        this.data = data;
    }
    public BlogResult(int code,String msg,T obj)
    {
        this.code = code;
        this.msg = msg;
        this.data = obj;
    }
    public static BlogResult build(int code, String msg) {
        return new BlogResult(code, msg);
    }
    public static BlogResult build(int code, String msg,Object data) {
        return new BlogResult(code, msg,data);
    }
    public static BlogResult ok(Object data) {
        return new BlogResult(data);
    }
    public static BlogResult ok(int code,Object data) {
        return new BlogResult(code,data);
    }
    public static BlogResult ok()
    {
        return new BlogResult();
    }
    /**
     * 没有object对象的转化
     *
     * @param json
     * @return
     */
    public static BlogResult format(String json) {
        try {
            return MAPPER.readValue(json, BlogResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 将json结果集转化为TaotaoResult对象
     *
     * @param jsonData json数据
     * @param clazz TaotaoResult中的object类型
     * @return
     */
    public static BlogResult formatToPojo(String jsonData, Class<?> clazz) {
        try {
            if (clazz == null) {
                return MAPPER.readValue(jsonData, BlogResult.class);
            }
            JsonNode jsonNode = MAPPER.readTree(jsonData);
            JsonNode data = jsonNode.get("data");
            Object obj = null;
            if (clazz != null) {
                if (data.isObject()) {
                    obj = MAPPER.readValue(data.traverse(), clazz);
                } else if (data.isTextual()) {
                    obj = MAPPER.readValue(data.asText(), clazz);
                }
            }
            return build(jsonNode.get("code").intValue(), jsonNode.get("msg").asText(), obj);
        } catch (Exception e) {
            return null;
        }
    }
}
